Page({
  data: {
    cards: [],          // 卡片数组
    flippedIndices: [], // 已翻转的卡片索引
    matchedPairs: 0,    // 已匹配的对数
    totalPairs: 0,      // 总对数
    attempts: 0,        // 尝试次数
    isProcessing: false,// 是否正在处理（防止快速点击）
    gameOver: false,    // 游戏是否结束
    timeSpent: 0,       // 游戏用时
    timer: null,        // 计时器
    columns: 4,         // 列数
    showAllMatched: true // 是否显示已匹配的卡片
  },

  onLoad() {
    // 获取选择的难度
    const difficulty = wx.getStorageSync('difficulty') || 'easy';
    this.initGame(difficulty);
  },

  // 初始化游戏
  initGame(difficulty) {
    let rows, cols, pairs;
    
    // 根据难度设置行列数
    switch(difficulty) {
      case 'easy':
        rows = 4;
        cols = 4;
        pairs = 8;
        break;
      case 'medium':
        rows = 4;
        cols = 6;
        pairs = 12;
        break;
      case 'hard':
        rows = 6;
        cols = 6;
        pairs = 18;
        break;
    }
    
    // 创建卡片数据
    const cards = this.createCards(pairs);
    
    // 设置数据
    this.setData({
      cards,
      totalPairs: pairs,
      matchedPairs: 0,
      attempts: 0,
      flippedIndices: [],
      gameOver: false,
      timeSpent: 0,
      columns: cols
    });
    
    // 开始计时
    this.startTimer();
  },

  // 创建卡片数组（使用数字和颜色作为图案）
  createCards(pairs) {
    const cards = [];
    const colors = [
      '#3a7bd5', '#4ecdc4', '#45b7d1', '#ff6b6b', '#ffda79', 
      '#ffaaa5', '#a77dc2', '#7ee8fa', '#ff8c42', '#66bb6a',
      '#ec407a', '#26a69a', '#8d6e63', '#78909c', '#5c6bc0',
      '#2979ff', '#ef5350', '#66bb6a'
    ];
    
    // 创建配对的卡片
    for (let i = 1; i <= pairs; i++) {
      // 确保颜色索引不超出范围
      const colorIndex = (i - 1) % colors.length;
      
      // 添加第一张卡片
      cards.push({
        value: i,
        color: colors[colorIndex],
        flipped: false,
        matched: false
      });
      
      // 添加配对的第二张卡片
      cards.push({
        value: i,
        color: colors[colorIndex],
        flipped: false,
        matched: false
      });
    }
    
    // 洗牌（随机排序）
    return this.shuffleArray(cards);
  },

  // 数组洗牌算法
  shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 翻转卡片
  flipCard(e) {
    const index = e.currentTarget.dataset.index;
    const { cards, flippedIndices, isProcessing, gameOver } = this.data;
    
    // 如果正在处理、游戏已结束、卡片已翻转或已匹配，则不执行操作
    if (isProcessing || gameOver || cards[index].flipped || cards[index].matched) {
      return;
    }
    
    // 如果已经有两张卡片翻转，则不执行操作
    if (flippedIndices.length >= 2) {
      return;
    }
    
    // 翻转当前卡片
    const newCards = [...cards];
    newCards[index].flipped = true;
    const newFlippedIndices = [...flippedIndices, index];
    
    this.setData({
      cards: newCards,
      flippedIndices: newFlippedIndices
    });
    
    // 如果已经翻转了两张卡片，检查是否匹配
    if (newFlippedIndices.length === 2) {
      this.setData({ attempts: this.data.attempts + 1 });
      this.checkForMatch();
    }
  },

  // 检查两张卡片是否匹配
  checkForMatch() {
    this.setData({ isProcessing: true });
    
    const { cards, flippedIndices, matchedPairs } = this.data;
    const index1 = flippedIndices[0];
    const index2 = flippedIndices[1];
    
    // 延迟检查，让玩家有时间看到两张卡片
    setTimeout(() => {
      const newCards = [...cards];
      let newMatchedPairs = matchedPairs;
      
      // 检查是否匹配
      if (newCards[index1].value === newCards[index2].value) {
        // 匹配成功
        newCards[index1].matched = true;
        newCards[index2].matched = true;
        newMatchedPairs++;
      } else {
        // 匹配失败，翻回
        newCards[index1].flipped = false;
        newCards[index2].flipped = false;
      }
      
      // 更新数据
      this.setData({
        cards: newCards,
        flippedIndices: [],
        matchedPairs: newMatchedPairs,
        isProcessing: false
      });
      
      // 检查游戏是否结束
      if (newMatchedPairs === this.data.totalPairs) {
        this.endGame();
      }
    }, 1000);
  },

  // 开始计时器
  startTimer() {
    // 清除之前的计时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    
    const startTime = Date.now() - (this.data.timeSpent * 1000);
    const timer = setInterval(() => {
      const currentTime = Date.now();
      const timeSpent = Math.floor((currentTime - startTime) / 1000);
      
      this.setData({
        timeSpent
      });
    }, 1000);
    
    this.setData({ timer });
  },

  // 结束游戏
  endGame() {
    // 停止计时器
    clearInterval(this.data.timer);
    
    this.setData({
      gameOver: true,
      timer: null
    });
  },

  // 再玩一次
  playAgain() {
    const difficulty = wx.getStorageSync('difficulty') || 'easy';
    this.initGame(difficulty);
  },

  // 返回主页
  goHome() {
    // 停止计时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    wx.navigateTo({
      url: '/pages/courses/tcs/tcs.js'
    });
  },

  // 返回上一页
  goBack() {
    // 停止计时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    wx.navigateBack();
  },

  onUnload() {
    // 页面卸载时停止计时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  }
});
    